﻿using OA.BLL;

using OA.Core;
using OA.Model;
using OA.Model.Other;
using OA.Model.View;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OA.Web.Attribute;
using OA.Model.DB;
using OA.Core.Helper;
using Microsoft.AspNetCore.Mvc.Rendering;
using OA.Model.Mapper;
using OA.Core.DataAccessHelper;
using OA.Core.EF;
using OA.Model.MyAttribute;
using Z.EntityFramework.Plus;
using OA.Core.Model;
using OA.Core.Other;
using OA.BLL.Web.Helpers;
using NetCoreHTMLToPDF;
using System.Text;

namespace OA.Web.Areas.Member.Controllers
{
    public class CustomFormController : BaseMemberController
    {
        private IMemoryCache _cache;
        private ICookie _cookie;
        private IHttpContextAccessor _accessor;
        public CustomFormController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
            _accessor = accessor;
        }

        public IActionResult Category(int id)
        {
            FormGroup infoFormGroup = this.dbContextFactory.DbContext.FormGroup.Where(m => m.ID == id).FirstOrDefault();
            if (infoFormGroup == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程分组不存在");
            }
            ViewBag.FormGroup = infoFormGroup;
            Expression<Func<CustomForm, bool>> where = m => m.FormGroupID == id && m.Status != -1;
            var result = this.GetAll<CustomForm, SimpleCustomForm2>(where, SimpleCustomForm2.Map);
            result = result.Where(m => this.CurrentPermissionCodes.Contains(m.Code)).ToList();
            ViewBag.PageKey = "002" + infoFormGroup.ID.ToString("D3");
            return View(result);
        }

        [MyActionFilter("002", "id")]
        [HttpGet]
        public IActionResult Index(int id, int p = 1, int size = 20)
        {
            ViewBag.CustomID = id;
            CustomForm infoCustomForm = this.GetInfo<CustomForm>(id);
            if (infoCustomForm == null)
            {
                ViewBag.ErrorMsg = "您请求的流程审批类型不存在";
            }
            else
            {
                ViewBag.CustomForm = infoCustomForm;
                FormGroup infoFormGroup = this.dbContextFactory.DbContext.FormGroup.Where(m => m.ID == infoCustomForm.FormGroupID).FirstOrDefault();
                if (infoFormGroup == null)
                {
                    ViewBag.ErrorMsg = "您请求的审批流程分组不存在";
                }
                else
                {
                    ViewBag.FormGroup = infoFormGroup;
                }
            }
            return View();
        }


        [MyActionFilter("002", "id")]
        [HttpGet]
        public IActionResult GetData(int id, string keyWord, int page = 1, int limit = 20)
        {
            Expression<Func<Voucher, bool>> whereExpression = m => m.Sponsor == EmpID;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                whereExpression = m => m.Title.Contains(keyWord);
            }
            Func<SimpleVoucher, int> orderExpression = m => m.ID;
            int rowCount = 0;
            var list = CVoucher.GetVoucherListByID(id, limit, page, whereExpression, SimpleVoucher.Map, orderExpression, false, ref rowCount); ;
            var result = new
            {
                code = "0",
                msg = "",
                count = rowCount,
                data = list
            };
            return Json(result);
        }


        [HttpGet]
        [MyActionFilter("002", "id")]
        public IActionResult Add(int id)
        {
            CustomForm infoCustomForm = this.dbContextFactory.GetInfo<CustomForm>(id);
            if (infoCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程不存在");
            }
            FormGroup infoFormGroup = this.dbContextFactory.DbContext.FormGroup.Where(m => m.ID == infoCustomForm.FormGroupID).FirstOrDefault();
            if (infoFormGroup == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程分组不存在");
            }
            ViewBag.FormGroup = infoFormGroup;
            ViewBag.PageKey = "002" + infoCustomForm.FormGroupID.ToString("D3");
            Voucher infoVoucher = new Voucher() { CustomFormID = id, Status = 1, DepartmentID = DepartmentID };
            List<ExtendField> extendFields = null;
            if (!string.IsNullOrWhiteSpace(infoCustomForm.ExtendField))
            {
                extendFields = JsonHelper.DeserializeList<ExtendField>(infoCustomForm.ExtendField);
            }

            if (extendFields == null)
            {
                extendFields = new List<ExtendField>();
            }

            if (extendFields.Where(m => m.Type == 99).Select(m => m.Values).Count() > 0)//有表格
            {
                var tableInfos = this.dbContextFactory.DbContext.TableInfo.ToList();
                foreach (var item in extendFields)
                {
                    if (item.Type == 99)
                    {
                        int tableID = 0;
                        if (Int32.TryParse(item.Values, out tableID))
                        {
                            item.Values = tableInfos.Where(m => m.ID == tableID).Select(m => m.ConfigContent).FirstOrDefault();
                        }
                    }
                }
            }

            ViewBag.CustomForm = infoCustomForm;
            ViewBag.ExtendFields = extendFields;
            ViewBag.DicExtend = new Dictionary<string, string>();
            List<ListItem> listPosition = this.dbContextFactory.DbContext.Database.SqlQuery<EmpPosition>($"Select * from EmployeePosition_Position where EmpID='{EmpID}'").Select(m => new ListItem() { Value = m.ID.ToString(), Text = m.Name.ToString() }).ToList();
            if (listPosition.Count == 0)
            {
                return Redirect("/Area/Member/Home/ShowInfo?msg=" + HttpUtility.UrlEncode("没有找到您的岗位信息，请联系HR!"));
                //提示需要添加岗位才可以操作
            }
            ViewBag.ListPosition = listPosition.GroupBy(p => new { p.Value, p.Text }).Select(g => g.First()).ToList(); //去重
            ViewBag.Positions = this.dbContextFactory.DbContext.Position.Where(m => m.Status != -1).Select(m => new { i = m.ID, n = m.Name, d = m.DepartmentID }).ToList();
            ViewBag.Departments = this.dbContextFactory.DbContext.Department.Where(m => m.Status != -1).Select(m => new { i = m.ID, n = m.Name, p = m.ParentDepartmentID }).ToList();
            ViewBag.Employees = this.dbContextFactory.DbContext.Employee.Where(m => m.Status != -1).Select(m => new { n = m.EmpName, i = m.EmpID }).ToList();
            ViewBag.EmployeePositions = this.dbContextFactory.DbContext.EmployeePosition.Where(m => m.Status != -1).Select(m => new { p = m.PositionID, e = m.EmpID }).ToList();
            return View(infoVoucher);
        }

        [HttpPost]
        [MyActionFilter("002", "id")]
        public IActionResult Add(Voucher info, Dictionary<string, string> dicExtend, List<CustomProcessNode> CustomProcessNode)
        {

            info.CreateDateTime = DateTime.Now;
            BaseResult baseResult = InitVoucher(info, dicExtend, CustomProcessNode);
            if (baseResult.State == 200)
            {
                var infoCustom = this.dbContextFactory.DbContext.CustomForm.Where(m => m.ID == info.CustomFormID).FirstOrDefault();

                VoucherMapper voucherMapper = new VoucherMapper();
                var dal = DataAccessor.Create<VoucherDbContext>();
                dal.ChangeMappingTable(typeof(Voucher), voucherMapper, info.CustomFormID);
                dal.Add<Voucher>(info);
                baseResult.Msg = "url:" + "/Member/CustomForm/Show?formID=" + info.ID.ToString() + "&customID=" + info.CustomFormID;
                return Json(baseResult);
            }
            else
            {
                baseResult.Msg = baseResult.Msg;
                return Json(baseResult);
            }
        }


        public BaseResult InitVoucher(Voucher info, Dictionary<string, string> dicExtend, List<CustomProcessNode> CustomProcessNode)
        {
            BaseResult baseResult = new BaseResult();
            CustomForm infoCustomForm = this.GetInfo<CustomForm>(info.CustomFormID);
            if (infoCustomForm == null)
            {
                baseResult.State = 400;
                baseResult.Msg = "页面不存在";
                return baseResult;
            }

            #region  获取扩展的部门 职员数据
            //dicExtend._EmpID  获取扩展的部门 职员数据

            var extendFields = JsonHelper.DeserializeList<ExtendField>(infoCustomForm.ExtendField);
            var tables = this.dbContextFactory.DbContext.TableInfo.ToList();
            if (extendFields.Count > 0)//非表格扩展字段处理
            {

                ///数据特殊处理的控件
                var list = extendFields.Where(m => m.Type == (int)TagEnum.Reference || m.Type == (int)TagEnum.Contact || m.Type == (int)TagEnum.Product || m.Type == (int)TagEnum.RelatedCompany || m.Type == (int)TagEnum.Supplier || m.Type == (int)TagEnum.Customer || m.Type == (int)TagEnum.CheckBox || m.Type == (int)TagEnum.MultipleReference || m.Type == (int)TagEnum.MultipleFlieUpload || m.Type == (int)TagEnum.MultipleImageUpload || m.Type == (int)TagEnum.Table).ToList();

                foreach (var item in list)
                {
                    if (item.Type == 17 || item.Type == 18)//多图上传,多文件
                    {
                        var values = _accessor.HttpContext.Request.Form["dicExtend." + item.Attribute].ToString();
                        List<string> files = values.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        values = JsonHelper.SerializeObject(files);
                        dicExtend[item.Attribute] = values;
                    }                     
                    else if (item.Type == 5) //多选择框
                    {
                        var values = _accessor.HttpContext.Request.Form["dicExtend." + item.Attribute].ToString();
                        var checkValues = values.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        if (checkValues.Count > 0)
                        {
                            dicExtend[item.Attribute] = string.Join(",", checkValues);
                        }
                        else
                        {
                            dicExtend[item.Attribute] = "";
                        }
                    }
                    else if(item.Type == 30 || item.Type==40|| item.Type == 41 || item.Type == 42 || item.Type == 43 || item.Type == 44)
                    {
                        if(dicExtend.ContainsKey(item.Attribute))
                        {
                            var oldValue = dicExtend[item.Attribute];
                            if (!string.IsNullOrWhiteSpace(oldValue))
                            {
                                dicExtend[item.Attribute] = oldValue.FromBase64();
                            }
                        }
                    }      
                    else if (item.Type == 31)//多个单据引用 dicExtend._Z[0].ID
                    {
                        List<SimpleApproval> references = new List<SimpleApproval>();
                        var nvc = _accessor.HttpContext.Request.Form;
                        for (int i = 0; ; i++)
                        {
                            string prefix = "dicExtend." + item.Attribute + "[" + i.ToString() + "].";
                            if (nvc[prefix + "Status"] == "1")
                            {
                                int CustomID = 0, FormID = 0;
                                if (Int32.TryParse(nvc[prefix + "CustomID"], out CustomID) && Int32.TryParse(nvc[prefix + "FormID"], out FormID) && !string.IsNullOrWhiteSpace(nvc[prefix + "Title"]) && !string.IsNullOrWhiteSpace(nvc[prefix + "No"]))
                                {
                                    references.Add(new SimpleApproval() { CustomID = CustomID, FormID = FormID, No = nvc[prefix + "No"], Title = nvc[prefix + "Title"] });
                                }
                            }
                            else if (string.IsNullOrWhiteSpace(nvc[prefix + "Status"]))
                            {
                                break;
                            }
                        }
                        dicExtend[item.Attribute] = JsonHelper.SerializeObject(references);
                    }
                    else if(item.Type==99)
                    {
                        int tableID = 0;
                        if(Int32.TryParse(item.Values,out tableID))
                        {                             
                            item.DefaultValue = this.dbContextFactory.DbContext.TableInfo.Where(m => m.ID == tableID).Select(m => m.ConfigContent).FirstOrDefault();
                        }                        
                    }
                }
            }

            #endregion


            #region 自定义流程及会签数据
            if (infoCustomForm.IsCustomProcess && CustomProcessNode != null)
            {
                info.TreeContent = JsonHelper.SerializeObject(CustomProcessNode.Where(m => m.Status != -1).ToList());
            }
            else
            {
                //判断流程上是否有会签节点

                info.TreeContent = "";
            }
            #endregion

            info.Sponsor = base.Info.EmpID;


            Position infoPosition = this.dbContextFactory.DbContext.Position.Where(m => m.ID == info.PositionID).FirstOrDefault();
            if (infoPosition == null || infoPosition.Status == -1)
            {
                baseResult.State = 400;
                baseResult.Msg = "您选择的岗位信息有误";
                return baseResult;
            }
            info.PositionID = infoPosition.ID;
            
            info.DepartmentID = infoPosition.DepartmentID;
            CacheHelper cacheHelper = new CacheHelper(_cache);
            info.DepartmentName = CDepartment.GetFullDepartmentNameByID(info.DepartmentID, cacheHelper.GetDepartments());
            info.SponsorName = Info.EmpName;
            info.Status = 0;            
            info.Extension = JsonConvert.SerializeObject(dicExtend);
            info.No = CVoucher.GetBills(info.CustomFormID);
            info.CustomFormContent = JsonConvert.SerializeObject(extendFields);
            return baseResult;
        }


        [HttpGet]
        [MyActionFilter("002", "id")]
        public IActionResult Edit(int id, int itemid)
        {

            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, id);

            Voucher infoVoucher = dal.GetByID<Voucher>(itemid);
            if (infoVoucher == null || infoVoucher.Sponsor != base.EmpID)
            {
                //非法的编辑
                return Redirect("/Area/Member/Home/ShowInfo?msg=" + HttpUtility.UrlEncode("非法操作!"));
            }

            CustomForm infoCustomForm = this.dbContextFactory.GetInfo<CustomForm>(id);
            if (infoCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程不存在");
            }

            FormGroup infoFormGroup = this.dbContextFactory.DbContext.FormGroup.Where(m => m.ID == infoCustomForm.FormGroupID).FirstOrDefault();
            if (infoFormGroup == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程分组不存在");
            }
            ViewBag.FormGroup = infoFormGroup;

            ViewBag.PageKey = "002" + infoCustomForm.FormGroupID.ToString("D3");
            

            List<ExtendField> extendFields = null;
            if (!string.IsNullOrWhiteSpace(infoCustomForm.ExtendField))
            {
                extendFields = JsonHelper.DeserializeList<ExtendField>(infoCustomForm.ExtendField);
            }

            if (extendFields == null)
            {
                extendFields = new List<ExtendField>();
            }

            if (extendFields.Where(m => m.Type == 99).Select(m => m.Values).Count() > 0)//有表格
            {
                var tableInfos = this.dbContextFactory.DbContext.TableInfo.ToList();
                foreach (var item in extendFields)
                {
                    if (item.Type == 99)
                    {
                        int tableID = 0;
                        if (Int32.TryParse(item.Values, out tableID))
                        {
                            item.Values = tableInfos.Where(m => m.ID == tableID).Select(m => m.ConfigContent).FirstOrDefault();
                        }
                    }
                }
            }

            ViewBag.CustomForm = infoCustomForm;
            ViewBag.ExtendFields = extendFields;
            ViewBag.DicExtend = JsonHelper.DeserializeObj<Dictionary<string, string>>(infoVoucher.Extension);

            List<ListItem> listPosition = this.dbContextFactory.DbContext.Database.SqlQuery<EmpPosition>($"Select * from EmployeePosition_Position where EmpID='{EmpID}'").Select(m => new ListItem() { Value = m.ID.ToString(), Text = m.Name.ToString() }).ToList();
            if (listPosition.Count == 0)
            {
                return Redirect("/Area/Member/Home/ShowInfo?msg=" + HttpUtility.UrlEncode("没有找到您的岗位信息!请联系HR"));
            }
            ViewBag.ListPosition = listPosition.GroupBy(p => new { p.Value, p.Text }).Select(g => g.First()).ToList();
             
            infoVoucher.CustomFormID = infoCustomForm.ID;
            return View("Add", infoVoucher);
        }

        [HttpPost]
        [MyActionFilter("002", "id")]
        public IActionResult Edit(int id, Voucher info, Dictionary<string, string> dicExtend, List<CustomProcessNode> CustomProcessNode)
        {
            Voucher infoVoucher = CVoucher.GetVoucherByID(info.CustomFormID, info.ID);
            if (infoVoucher == null)
            {
                return Redirect("/Area/Member/Home/ShowInfo?msg=" + HttpUtility.UrlEncode("没有找到该表单数据!"));
            }
            if (infoVoucher.Status > 0)
            {
                return Redirect("/Area/Member/Home/ShowInfo?msg=" + HttpUtility.UrlEncode("已发起的单据不允许再修改!"));
            }
            info.No = infoVoucher.No;
            info.CreateDateTime = infoVoucher.CreateDateTime;
            BaseResult baseResult = InitVoucher(info, dicExtend, CustomProcessNode);


            if (baseResult.State == 200)
            {
                CVoucher.UpdateVoucherByID(info, info.CustomFormID);
                baseResult.Msg = "url:" + "/Member/CustomForm/Show?formID=" + info.ID.ToString() + "&customID=" + info.CustomFormID;
                return Json(baseResult);
            }
            else
            {
                return Json(baseResult);
            }

        }

        public IActionResult Show(int customID, int formID, string type,bool isPrint=false)
        {
            ViewBag.Type = type;

            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customID);

            Voucher infoVoucher = CVoucher.GetVoucherByID(customID, formID);
            if (infoVoucher == null)
            {
                return Redirect("/Member/Tips/Index?msg=该单据不存在");
            }

            if (infoVoucher.Sponsor != Info.EmpID && !infoVoucher.SupervisingEmpID.Contains(Info.EmpID))
            {
                Mailbox tempMailbox = this.dbContextFactory.DbContext.Mailbox.Where(m => m.CustomFormID == customID && m.FormID == formID && m.ToEmpID == Info.EmpID).FirstOrDefault();
                if (tempMailbox == null)
                {
                    return Redirect("/Member/Tips/Index?msg=您没有该单据的查看权限");
                }
            }

            CustomForm infoCustomForm = this.dbContextFactory.GetInfo<CustomForm>(customID);

            if (infoCustomForm == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程不存在");
            }

            FormGroup infoFormGroup = this.dbContextFactory.DbContext.FormGroup.Where(m => m.ID == infoCustomForm.FormGroupID).FirstOrDefault();
            if (infoFormGroup == null)
            {
                return Redirect("/Member/Tips/Index?msg=您请求的审批流程分组不存在");
            }
            ViewBag.FormGroup = infoFormGroup;
            List<ExtendField> extendFields = null;
            if (!string.IsNullOrWhiteSpace(infoVoucher.CustomFormContent))
            {
                extendFields = JsonHelper.DeserializeList<ExtendField>(infoVoucher.CustomFormContent);
            }
            
            if (extendFields == null)
            {
                extendFields = new List<ExtendField>();
            }
            CVoucher objVoucher = new CVoucher();
            objVoucher.Map(infoVoucher, infoCustomForm, _cache);


            Dictionary<string, string> dicValue = JsonHelper.DeserializeObj<Dictionary<string, string>>(infoVoucher.Extension);


            ViewBag.CustomForm = infoCustomForm;
            ViewBag.ExtendFields = extendFields;//表单结构

            var tableList = this.dbContextFactory.DbContext.TableInfo.ToList();
           
            if (infoCustomForm.IsCustomView && !string.IsNullOrWhiteSpace(infoCustomForm.PrintTemplate)&& isPrint)
            {
                Dictionary<string, string> dicValue2 = new Dictionary<string, string>();
                string printTemplate = infoCustomForm.PrintTemplate;
                var tables = extendFields.Where(m => m.Type == 99).ToList();
                foreach (var table in tables)
                {
                    if(dicValue.ContainsKey(table.Attribute))
                    {                       
                        List<Dictionary<string, string>> model = JsonHelper.DeserializeList<Dictionary<string, string>> (dicValue[table.Attribute]);                        
                        this.ViewData["TableAttribute"] = table.Attribute;
                        this.ViewData["TableName"] = table.Name;
                        this.ViewData["TableInfo"] = table.DefaultValue;
                        var partialViewHtml = this.RenderViewAsync("TableInfoView", model, true);
                        dicValue2.Add(table.Name +"_"+ table.Attribute, partialViewHtml);
                    }                   
                }

                var idNames = extendFields.Where(m => m.Type>=40&&m.Type<=44).ToList();
                foreach (var idName in idNames)
                {
                    if (dicValue.ContainsKey(idName.Attribute))
                    {
                        string value = dicValue[idName.Attribute];
                        SimpleOtherInfo simpleOtherInfo = JsonHelper.DeserializeObj<SimpleOtherInfo>(value);
                        if(simpleOtherInfo!=null)
                        {
                            dicValue2.Add(idName.Name + "_" + idName.Attribute, simpleOtherInfo.Name);
                        }
                        
                    }
                }

                var references = extendFields.Where(m => m.Type >= 30 && m.Type <= 31).ToList();
                foreach (var reference in references)
                {
                    if (dicValue.ContainsKey(reference.Attribute))
                    {
                        string value = dicValue[reference.Attribute];
                        var simpleApprovals = JsonHelper.DeserializeObj<List<SimpleApproval>>(value);
                        if (simpleApprovals != null&& simpleApprovals.Count>0)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append("<table class=\"layui-table\" style=\"width:100%;\"><thead><th style=\"text-align:center;\">单据编号</th><th style=\"text-align:center;\">标题</th></thead><tbody>");
                            foreach (var simpleApproval in simpleApprovals)
                            {
                                sb.Append($"<tr><td>{simpleApproval.No}</td><td>{simpleApproval.Title}</td></tr>");
                            }
                            sb.Append("</tbody></table>");
                            dicValue2.Add(reference.Name + "_" + reference.Attribute, sb.ToString());
                        }
                        else
                        {
                            dicValue2.Add(reference.Name + "_" + reference.Attribute, "");
                        }

                    }
                }

                //ApprovalProcess__上级审批

                List<ApprovalNode> nodes = JsonHelper.DeserializeList<ApprovalNode>(infoVoucher.ApprovalNodeContent);
                var shangjis = nodes.Where(m => m.TypeID == 3).ToList();
                if(shangjis.Count==0)
                {
                    dicValue2.Add("ApprovalProcess__上级审批", "");
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    int width = 100 / shangjis.Count;
                    foreach (var shangji in shangjis)
                    {
                        sb.Append($"<div style='width:{width}%;float:left;display:block;'>{shangji.Name}:{shangji.EmpName}</div>");
                    }
                    dicValue2.Add("ApprovalProcess__上级审批", sb.ToString());
                }

                foreach (var node in nodes)
                {
                    if (node.TypeID == 3) continue;
                    string key = "ApprovalProcess__" + node.NodeName;
                    if(dicValue2.ContainsKey(key))
                    {
                        dicValue2[key] = dicValue2[key] + "," + node.EmpName;
                    }
                    else
                    {
                        dicValue2.Add(key, node.EmpName);
                    }
                    
                }

                dicValue2.Add("主题_T", infoVoucher.Title);
                dicValue2.Add("主办部门_D", infoVoucher.DepartmentName);
                dicValue2.Add("主办人_S", infoVoucher.SponsorName);
                dicValue2.Add("主办部门+主办人_B", infoVoucher.DepartmentName + " " + infoVoucher.SponsorName);
                dicValue2.Add("主办部门+主办岗位_C", infoVoucher.DepartmentName + " " + infoVoucher.PositionName);
                dicValue2.Add("主办岗位+主办人_E", infoVoucher.PositionName + " " + infoVoucher.SponsorName);
                dicValue2.Add("主办部门+主办岗位+主办人_F", infoVoucher.DepartmentName + " " + infoVoucher.PositionName + " " + infoVoucher.SponsorName);
                dicValue2.Add("申请时间_A", infoVoucher.ApplicationDate.ToString2());
                dicValue2.Add("主办岗位_P", infoVoucher.PositionName);
                dicValue2.Add("单据编号_N", infoVoucher.No);
                //单据编号_N
                foreach (var extendField in extendFields)
                {
                    if (dicValue2.ContainsKey(extendField.Name + "_" + extendField.Attribute)) continue;
                    if(extendField.Type!=99&& dicValue.ContainsKey(extendField.Attribute))
                    {
                        if(extendField.Type==17|| extendField.Type==18)
                        {
                            List<string> files = JsonHelper.DeserializeList<string>(dicValue[extendField.Attribute]);
                            StringBuilder sb = new StringBuilder();
                            int tempIndex = 1;
                            foreach (var file in files)
                            {
                              sb.AppendFormat("<p>文件{0}：{1}</p>",tempIndex, CommonHelper.GetFileName(file)) ;
                                tempIndex++;
                            }
                            dicValue2.Add(extendField.Name + "_" + extendField.Attribute, sb.ToString());
                        }
                        else
                        {
                            dicValue2.Add(extendField.Name + "_" + extendField.Attribute, dicValue[extendField.Attribute]);
                        }                        
                    }
                }

                foreach (var key in dicValue2.Keys)
                {
                    printTemplate = printTemplate.Replace(key, dicValue2[key]);
                }
                
                this.ViewData["PrintTemplate"] = printTemplate;
                var viewHtml = this.RenderViewAsync("Show2", infoVoucher, false);

                var converter = new HtmlConverter();
                var pageOrientation = NetCoreHTMLToPDF.Enums.PageOrientation.Portrait;
                if(infoCustomForm.HorizontalPrinting)
                {
                    pageOrientation = NetCoreHTMLToPDF.Enums.PageOrientation.Landscape;
                }
                var bytes = converter.FromHtmlString(viewHtml, pageOrientation: pageOrientation);
                System.IO.File.WriteAllBytes("html.pdf", bytes);
                FileResult fileResult = new FileContentResult(bytes, "application/pdf");
                return fileResult;

            }
            else
            {
                return View(infoVoucher);
            }

        }


        [HttpGet]
        [MyActionFilter("002", "cid")]
        public IActionResult Delete(int id, int cid)
        {
            BaseResult baseResult = new BaseResult();
            var info = CVoucher.GetVoucherByID(cid, id);
            if (info.Status != 1)
            {
                baseResult.State = 400;
                baseResult.Msg = "没有为发起的申请才可以删除，当前单据状态为：" + info.StatusName;
            }
            else
            {
                CVoucher.DeleteVoucherByID(cid, id);
            }
            return Json(baseResult);
        }


        [HttpGet]
        public IActionResult Sponsor(int customID, int formID)
        {
            CApproval objApproval = new CApproval(_cache);
            return Json(objApproval.Sponsor(customID, formID, this.Info));
        }

        /// <summary>
        /// 抄送
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult CarbonCopy(int id)
        {
            Approval infoApproval = this.dbContextFactory.DbContext.Approval.Where(m => m.ID == id).FirstOrDefault();
            if (infoApproval == null || infoApproval.SponsorEmpID != base.EmpID)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到原始单据");
            }
            Voucher infoVoucher = CVoucher.GetVoucherByID(infoApproval.CustomID, infoApproval.FormID);
            if (infoVoucher == null)
            {
                return Redirect("/Member/Tips/Index?msg=没有找到原始单据");
            }
            if (infoVoucher.Sponsor != Info.EmpID)
            {
                return Redirect("/Member/Tips/Index?msg=非法的操作，请刷新页面检查是否登录超时");
            }
            ViewBag.InfoApproval = infoApproval;
            return View(infoVoucher);
        }

        [HttpPost]
        public IActionResult CarbonCopy(int customFormID, int formID, List<CountersignEmployee> countersignEmployees)
        {
            BaseResult result = new BaseResult();
            if (countersignEmployees == null)
            {
                result.State = 400;
                result.Msg = "没有找到任何抄送人员";
                return Json(result);
            }

            countersignEmployees = countersignEmployees.Where(m => m.Status != -1).ToList();
            if (countersignEmployees.Count == 0)
            {
                result.State = 400;
                result.Msg = "没有找到任何抄送人员";
                return Json(result);
            }

            Voucher infoVoucher = CVoucher.GetVoucherByID(customFormID, formID);
            if (infoVoucher == null)
            {
                result.State = 400;
                result.Msg = "没有找到该抄送单据";
                return Json(result);
            }
            if (infoVoucher.Sponsor != Info.EmpID)
            {
                result.State = 400;
                result.Msg = "您没有该抄送单据的抄送权限";
                return Json(result);
            }


            CacheHelper cacheHelper = new CacheHelper(_cache);
            List<Department> listDepartment = cacheHelper.GetDepartments();
            List<Position> listPosition = cacheHelper.GetPositions();
            List<EmployeePosition> listEmployeePosition = cacheHelper.GetEmployeePositions();
            List<Employee> listEmployee = cacheHelper.GetEmployees();

            Position myPosition = listPosition.Where(m => m.ID == infoVoucher.PositionID).FirstOrDefault();
            string fromEmpName = string.Empty;
            string fromPositionName = string.Empty;
            string fromDepartmentName = string.Empty;
            if (myPosition != null)
            {
                fromPositionName = myPosition.Name;
                Department fromDepartment = listDepartment.Where(m => m.ID == myPosition.DepartmentID).FirstOrDefault();
                if (fromDepartment != null)
                {
                    fromDepartmentName = fromDepartment.Name;
                }

            }
            Employee fromEmployee = listEmployee.Where(m => m.EmpID == infoVoucher.Sponsor).FirstOrDefault();
            if (fromEmployee != null)
            {
                fromEmpName = fromEmployee.EmpName;
            }

            var exists = this.dbContextFactory.DbContext.Mailbox.Where(m => m.CustomFormID == customFormID && m.FormID == formID).Select(m => m.ToEmpID).ToList();
            exists.Add(infoVoucher.Sponsor);
            List<Mailbox> listMailbox = new List<Mailbox>();
            foreach (CountersignEmployee item in countersignEmployees)
            {
                if (exists.Where(m => m == item.EmpID).FirstOrDefault() != null) continue;
                Mailbox infoMailbox = new Mailbox();
                Position itemPosition = listPosition.Where(m => m.ID == item.PositionID).FirstOrDefault();
                if (itemPosition == null) continue;
                infoMailbox.ToPositionName = itemPosition.Name;
                Department infoDepartment = listDepartment.Where(m => m.ID == itemPosition.DepartmentID).FirstOrDefault();
                if (infoDepartment == null) continue;
                infoMailbox.ToDepartmentName = infoDepartment.Name;
                Employee itemEmployee = listEmployee.Where(m => m.EmpID == item.EmpID).FirstOrDefault();
                infoMailbox.ToEmpID = itemEmployee.EmpID;
                if (itemEmployee == null) continue;
                infoMailbox.No = infoVoucher.No;
                infoMailbox.ToEmpName = itemEmployee.EmpName;
                infoMailbox.FromDepartmentName = fromDepartmentName;
                infoMailbox.FromEmpName = fromEmpName;
                infoMailbox.FromPositionName = fromPositionName;
                infoMailbox.FromEmpID = infoVoucher.Sponsor;
                infoMailbox.CustomFormID = customFormID;
                infoMailbox.FormID = formID;
                infoMailbox.Title = infoVoucher.Title;
                listMailbox.Add(infoMailbox);
            }
            if (listMailbox.Count > 0)
            {
                try
                {
                    this.AddRange<Mailbox>(listMailbox);
                }
                catch (Exception ex)
                {
                    result.State = 400;
                    result.Msg = "数据库操作异常!请联系管理员";
                    return Json(result);
                }
            }
            return Json(result);
        }


        //public IActionResult AddPoint(int id)
        //{
        //    Voucher infoVoucher = this.GetInfo<Voucher>(id);
        //    if (infoVoucher == null)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=没有找到该审批单据");
        //    }
        //    if (infoVoucher.Sponsor != Info.EmpID)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=您没有该审批单据的添加节点权限");
        //    }
        //    infoVoucher.CountersignEmployees = JsonHelper.DeserializeList<CountersignEmployee>(infoVoucher.Countersign);
        //    CCountersignEmployee objCountersignEmployee = new CCountersignEmployee();
        //    objCountersignEmployee.Map(infoVoucher.CountersignEmployees);


        //    int maxApproval = 0;
        //    Approval lastApproval = this.dbContextFactory.DbContext.Approval.Where(m => m.VoucherID == id && m.TypeID == 0).OrderByDescending(m => m.Step).FirstOrDefault();
        //    if (lastApproval != null)
        //    {
        //        maxApproval = lastApproval.Step;
        //    }
        //    int maxStep = infoVoucher.CountersignEmployees.Max(m => m.Step);

        //    List<SelectListItem> listSelectItem = new List<SelectListItem>();
        //    for (int i = maxApproval; i <= maxStep; i++) {

        //        string[] Employees = infoVoucher.CountersignEmployees.Where(m => m.Step == i).Select(m => m.EmpName).ToArray();
        //        if (Employees == null || Employees.Length == 0) continue;

        //        SelectListItem item = new SelectListItem();
        //        item.Value = (-i).ToString();
        //        item.Text = $"在{string.Join(",", Employees)}处插入";
        //        listSelectItem.Add(item);

        //        SelectListItem item2 = new SelectListItem();
        //        item2.Value = i.ToString();
        //        item2.Text = $"在{string.Join(",", Employees)}之后插入";
        //        listSelectItem.Add(item2);
        //    }
        //    ViewBag.SelectListItem = listSelectItem;
        //    ViewBag.MaxApproval = maxApproval;
        //    return View(infoVoucher);
        //}

        //[HttpPost]
        //public IActionResult AddPoint(int id, int step, int positionID, string empID)
        //{

        //    BaseResult result = new BaseResult();
        //    Voucher infoVoucher = this.GetInfo<Voucher>(id);
        //    if (infoVoucher == null)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=没有找到该审批单据");
        //    }
        //    if (infoVoucher.Sponsor != Info.EmpID)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=您没有该审批单据的添加节点权限");
        //    }

        //    EmployeePosition ep = this.dbContextFactory.DbContext.EmployeePosition.Where(m => m.PositionID == positionID && m.EmpID == empID && m.Status != -1).FirstOrDefault();
        //    if (ep == null)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=您提交的数据有误!请刷新页面重试");
        //    }

        //    infoVoucher.CountersignEmployees = JsonHelper.DeserializeList<CountersignEmployee>(infoVoucher.Countersign);
        //    int maxApproval = 0;

        //    Approval lastApproval = this.dbContextFactory.DbContext.Approval.Where(m => m.VoucherID == id && m.TypeID == 0).OrderByDescending(m => m.Step).FirstOrDefault();
        //    if (lastApproval != null)
        //    {
        //        maxApproval = lastApproval.Step;
        //    }
        //    if (step < 0)
        //    {
        //        if (-step < maxApproval)
        //        {
        //            result.State = 400;
        //            result.Msg = "节点插入位置不正确,<p>可能是审批发生了变化,请刷新页面重试</p>";
        //            return Json(result);
        //        }
        //    }
        //    else
        //    {
        //        if (step < maxApproval)
        //        {
        //            result.State = 400;
        //            result.Msg = "节点插入位置不正确,<p>可能是审批发生了变化,请刷新页面重试</p>";
        //            return Json(result);
        //        }
        //    }

        //    Voucher updateVoucher = new Voucher();
        //    Approval infoApproval = null;
        //    if (-step == maxApproval || (lastApproval.Status > 1 && step == maxApproval))//如果是增加到当前审批步骤或审批的最后节点
        //    {
        //        infoApproval = new Approval();
        //        CacheHelper cacheHelper = new CacheHelper();
        //        List<Employee> listEmployee = cacheHelper.GetEmployees();
        //        List<Department> listDepartment = cacheHelper.GetDepartments();
        //        List<Position> listPosition = cacheHelper.GetPositions();
        //        Employee infoEmployee = listEmployee.Where(m => m.EmpID == empID).FirstOrDefault();
        //        if (infoEmployee == null)
        //        {
        //            result.State = 400;
        //            result.Msg = "没有找到你添加的审批人员信息";
        //            return Json(result);
        //        }
        //        Position infoPosition = listPosition.Where(m => m.ID == positionID).FirstOrDefault();
        //        if (infoPosition == null)
        //        {
        //            result.State = 400;
        //            result.Msg = "没有找到你添加的审批人员的岗位信息";
        //            return Json(result);
        //        }
        //        Department infoDepartment = listDepartment.Where(m => m.ID == infoPosition.DepartmentID).FirstOrDefault();
        //        if (infoDepartment == null)
        //        {
        //            result.State = 400;
        //            result.Msg = "没有找到你添加的审批人员的部门信息";
        //            return Json(result);
        //        }
        //        if (string.IsNullOrWhiteSpace(infoVoucher.CurrentApprover))
        //        {
        //            infoVoucher.CurrentApprover = infoEmployee.EmpName;
        //        }
        //        else
        //        {
        //            infoVoucher.CurrentApprover += "," + infoEmployee.EmpName;
        //        }
        //        infoApproval.DepartmentID = infoDepartment.ID;
        //        infoApproval.DepartmentName = infoDepartment.Name;
        //        infoApproval.EmpID = infoEmployee.EmpID;
        //        infoApproval.EmpName = infoEmployee.EmpName;
        //        infoApproval.PointType = 2;
        //        infoApproval.PositionID = infoPosition.ID;
        //        infoApproval.PositionName = infoPosition.Name;
        //        infoApproval.SourceEmpID = infoVoucher.Sponsor;
        //        infoApproval.SourceEmpName = "追加节点";
        //        infoApproval.Status = 0;
        //        infoApproval.Step = -step;
        //        infoApproval.TypeID = 0;
        //        infoApproval.VoucherID = infoVoucher.ID;
        //    }
        //    if (step < 0)
        //    {
        //        infoVoucher.CountersignEmployees.Add(new CountersignEmployee()
        //        {
        //            Step = -step,
        //            EmpID = empID,
        //            PositionID = positionID
        //        });
        //    }
        //    else
        //    {

        //        infoVoucher.CountersignEmployees.Where(m => m.Step > step).ToList().ForEach(m => m.Step = m.Step + 1);
        //        infoVoucher.CountersignEmployees.Add(new CountersignEmployee()
        //        {
        //            Step = step + 1,
        //            EmpID = empID,
        //            PositionID = positionID
        //        });
        //    }
        //    updateVoucher.Countersign = JsonConvert.SerializeObject(infoVoucher.CountersignEmployees.OrderBy(m => m.Step).ToList());
        //    if (infoApproval == null)
        //    {
        //        this.Update<Voucher>(infoVoucher, updateVoucher, new string[] { "Countersign" });
        //    }
        //    else
        //    {
        //        using (var trn = this.dbContextFactory.DbContext.Database.BeginTransaction())
        //        {
        //            try
        //            {
        //                if (step < 0)
        //                {
        //                    Expression<Func<Approval, bool>> where = m => m.VoucherID == infoVoucher.ID && m.Step == -step;
        //                    Approval updateApproval = new Approval();
        //                    updateApproval.PointType = 2;
        //                    this.UpdateByWhere<Approval>(where, updateApproval, new string[] { "PointType" });
        //                }
        //                updateVoucher.Status = 2;
        //                this.Update<Voucher>(infoVoucher, updateVoucher, new string[] { "Countersign", "CurrentApprover", "Status" });
        //                this.AddInfo<Approval>(infoApproval);
        //                trn.Commit();
        //            }
        //            catch
        //            {
        //                trn.Rollback();
        //                result.State = 400;
        //                result.Msg = "数据库操作异常!请联系管理员</p>";
        //                return Json(result);
        //            }
        //        }
        //    }
        //    return Json(result);
        //}

        //[HttpGet]
        //public IActionResult DeletePoint(int id, int step, string empID)
        //{
        //    BaseResult result = new BaseResult();

        //    Voucher infoVoucher = this.GetInfo<Voucher>(id);
        //    if (infoVoucher == null)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=没有找到该审批单据");
        //    }
        //    if (infoVoucher.Sponsor != Info.EmpID)
        //    {
        //        return Redirect("/Member/Tips/Index?msg=您没权限对该审批单据的节点进行删除");
        //    }


        //    infoVoucher.CountersignEmployees = JsonHelper.DeserializeList<CountersignEmployee>(infoVoucher.Countersign);
        //    if (infoVoucher.CountersignEmployees == null || infoVoucher.CountersignEmployees.Count == 0)
        //    {
        //        result.State = 400;
        //        result.Msg = "没有找到该审批节点";
        //        return Json(result);
        //    }

        //    Approval approval = this.dbContextFactory.DbContext.Approval.Where(m => m.VoucherID == id && m.Step == step && m.EmpID == empID).FirstOrDefault();
        //    if (approval != null)
        //    {
        //        if (approval.Status == 0)
        //        {
        //            result.State = 400;
        //            result.Msg = "当前审批节点正在审批中,不能删除";
        //        }
        //        else
        //        {
        //            result.State = 400;
        //            result.Msg = "当前审批节点已审批,不能删除";
        //        }
        //        return Json(result);
        //    }

        //    List<CountersignEmployee> currentStepEmployee = infoVoucher.CountersignEmployees.Where(m => m.Step == step).ToList();
        //    CountersignEmployee infoCountersignEmployee = currentStepEmployee.Where(m => m.EmpID == empID).FirstOrDefault();
        //    if (infoCountersignEmployee != null)
        //    {
        //        infoVoucher.CountersignEmployees.Remove(infoCountersignEmployee);
        //        if (currentStepEmployee.Count == 1)
        //        {
        //            infoVoucher.CountersignEmployees.Where(m => m.Step > step).ToList().ForEach(m => m.Step = m.Step - 1);
        //            Voucher updateVoucher = new Voucher();
        //            updateVoucher.Countersign = JsonConvert.SerializeObject(infoVoucher.CountersignEmployees.OrderBy(m => m.Step).ToList());
        //            this.Update<Voucher>(infoVoucher, updateVoucher, new string[] { "Countersign" });
        //        }
        //    }
        //    else
        //    {
        //        result.State = 400;
        //        result.Msg = "没有找到该审批节点";
        //        return Json(result);
        //    }

        //    return Json(result);
        //}

        /// <summary>
        /// 撤回
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Revocation(int id)
        {
            BaseResult result = new BaseResult();
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            var approvalInfo = dal.GetMany<Approval>(m => m.ID == id).FirstOrDefault();
            if (approvalInfo == null)
            {
                result.State = 400;
                result.Msg = "没有找到该发起信息";
                return Json(result);
            }
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, approvalInfo.CustomID);
            Voucher infoVoucher = dal.GetByID<Voucher>(approvalInfo.FormID);
            if (infoVoucher == null || infoVoucher.Sponsor != Info.EmpID)
            {
                result.State = 400;
                result.Msg = "没有找到该发起信息";
                return Json(result);
            }
            if (infoVoucher.Status != 1)
            {
                result.State = 400;
                result.Msg = "非审批状态中的单据不能撤回";
                return Json(result);
            }

            var dbContext = dal.GetDbContext();
            using (var trn = dbContext.Database.BeginTransaction())
            {
                try
                {
                    approvalInfo.Status = 2;
                    approvalInfo.FinishTime = DateTime.Now;
                    dbContext.Set<Approval>().Update(approvalInfo);
                    dbContext.Set<ApprovalItem>().Where(m => m.ApprovalID == approvalInfo.ID).Update(m => new ApprovalItem() { Status = 5 });
                    infoVoucher.Status = 2;
                    infoVoucher.FinishTime = approvalInfo.FinishTime;
                    dbContext.Set<Voucher>().Update(infoVoucher);
                    dal.Save();
                    trn.Commit();
                }
                catch (Exception ex)
                {
                    trn.Rollback();
                    result.State = 400;
                    result.Msg = "数据库操作异常!请联系管理员";
                    return Json(result);
                }
                return Json(result);
            }
        }


    }
    
}